//
//  ScoreListViewController.m
//  edu
//
//  Created by baobaodp on 13-8-26.
//  Copyright (c) 2013年 baobaodp. All rights reserved.
//

#import "ScoreListViewController.h"
#import "ScoreListCell.h"

#import "ScoreDetailViewController.h"
#import "RankViewController.h"
#import "RankListViewController.h"
#import "DBbase.h"
#import "EduViewController.h"
#import "UzysSlideMenu.h"
#import "UzysSMMenuItem.h"
#import "KxMenu.h"
#import "RNGridMenu.h"
#import "LineNodeChart.h"
#import "PieChart.h"
#import "ChartViewController.h"

//#import "Navbar.h"

@interface ScoreListViewController ()

@end

@implementation ScoreListViewController

@synthesize isSelfInfo;
@synthesize condition;
@synthesize studentInfo;
@synthesize undoManager;
@synthesize score;
@synthesize stuName;
@synthesize classRank;
@synthesize gradeRank;
@synthesize imgView;
@synthesize menuItems;
@synthesize imgNames;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.isODRefresh = FALSE;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self setTitle:@"成绩列表"];

    if(isSelfInfo == true){     
//        UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:@"排名" style:UIBarButtonItemStylePlain target:self action:@selector(showPM)];
//        self.navigationItem.rightBarButtonItem = backButton;
        
        //[self.navigationItem setRightItemWithTarget:self action:@selector(showPM) title:@"排名"];
        //考试信息
        [self loadTestInfo :userEntry.userInfo];
        
        [self initChartMenu];
        
        [self.chartBtn setHidden:FALSE];
        [self.classRankBtn setHidden:FALSE];
        [self.gradeRankBtn setHidden:FALSE];
    }else{
        //考试信息
        [self loadTestInfo :self.studentInfo];
        
        
        [self.chartBtn setHidden:true];
        [self.classRankBtn setHidden:true];
        [self.gradeRankBtn setHidden:true];
    }
    
    self.imgNames = [NSArray arrayWithObjects:@"Chart_Graph",
                     @"yuwen",
                     @"match",
                     @"blackboard",
                     @"lizong",
                     @"Art of Chemistry",
                     @"chameleon",
                     @"File History-01",
                     @"hu_jintao",
                     @"earth",nil];
    
}

/**
 * 初始化统计图菜单
 */
-(void) initChartMenu
{
//    self.menuItems =
//    @[
//      
//      [KxMenuItem menuItem:@"ACTION MENU 1234456"
//                     image:nil
//                    target:nil
//                    action:NULL],
//      
//      [KxMenuItem menuItem:@"Share this"
//                     image:[UIImage imageNamed:@"icon_Aim"]
//                    target:self
//                    action:@selector(pushMenuItem:)],
//      
//      [KxMenuItem menuItem:@"Check this menu"
//                     image:nil
//                    target:self
//                    action:@selector(pushMenuItem:)],
//      
//      [KxMenuItem menuItem:@"Reload page"
//                     image:[UIImage imageNamed:@"icon_Aim"]
//                    target:self
//                    action:@selector(pushMenuItem:)],
//      
//      [KxMenuItem menuItem:@"Search"
//                     image:[UIImage imageNamed:@"icon_Aim"]
//                    target:self
//                    action:@selector(pushMenuItem:)],
//      
//      [KxMenuItem menuItem:@"Go home"
//                     image:[UIImage imageNamed:@"icon_Aim"]
//                    target:self
//                    action:@selector(pushMenuItem:)],
//      ];

    self.menuItems=@[
                     [[RNGridMenuItem alloc] initWithImage:[UIImage imageNamed:@"chart_curve"] title:@"班级排名"],
                     [[RNGridMenuItem alloc] initWithImage:[UIImage imageNamed:@"chart_curve"] title:@"班级成绩"],
                     [[RNGridMenuItem alloc] initWithImage:[UIImage imageNamed:@"chart_curve"] title:@"年级排名"],
                     [[RNGridMenuItem alloc] initWithImage:[UIImage imageNamed:@"chart_curve"] title:@"年级成绩"],
                     [[RNGridMenuItem alloc] initWithImage:[UIImage imageNamed:@"Chart_Pie"] title:@"成绩饼图"]
                     ];
}

- (void) pushMenuItem:(id)sender
{
    NSLog(@"%@", sender);
}

/**
 *菜单响应
 */
- (void)gridMenu:(RNGridMenu *)gridMenu willDismissWithSelectedItem:(RNGridMenuItem *)item atIndex:(NSInteger)itemIndex {
    NSLog(@"Dismissed with item %d: %@", itemIndex, item.title);
    switch (itemIndex) {
        case 0:
            //班级排名
            [self openChar:@"班级排名曲线图" div:@"1" type:@"rank" seriesType:@"line" valueReverse :TRUE];
            break;
        case 1:
            //班级成绩
            [self openChar:@"班级成绩曲线图" div:@"1" type:@"R_Souce" seriesType:@"line" valueReverse :FALSE];
            break;
        case 2:
            //年级排名
            [self openChar:@"年级排名曲线图" div:@"2" type:@"rank" seriesType:@"line"valueReverse :TRUE];
            break;
        case 3:
            //年级成绩
            [self openChar:@"年级成绩曲线图" div:@"2" type:@"R_Souce" seriesType:@"line" valueReverse :FALSE];
            break;
        case 4:
            //成绩饼图
            [self openPicChar];
            break;
        default:
            break;
    }
}

-(void) openPicChar
{
    ChartViewController *detailViewController = [[ChartViewController alloc] initWithNibName:@"ChartViewController" bundle:nil];
    
    PieChart *chart = [[PieChart alloc]init];
    
    //DATA
    NSString *ptn_Id = [self.condition getFieldValueByName:@"ptn_Id"];
    
    NSString *stu_Id = [userEntry.userInfo getFieldValueByName:@"stu_Id"];
    
    NSString *querySql = [NSString stringWithFormat:@"select distinct T1.* ,T4.* "
                          "from T_Result T1 left join T_LessonTch T2 on T1.lesson_Tch_Id = T2.lesson_Tch_Id left join T_Lesson T3 on T2.lesson_ID = T3.lesson_ID left join M_Lesson T4 on T3.lesson_CD = T4.lesson_CD where T1.ptn_Id ='%@' and T1.stu_Id = '%@' " ,ptn_Id,stu_Id];
    
    const char *sql = [querySql UTF8String];
    
    
    chart.title = @"成绩分布";
    
    [chart addSeries:@"R_Souce" name:@"lesson_Name"];
    
    chart.dataSource = getDbRecords(sql,@"T_Rank",[NSArray arrayWithObjects:@"Rank_Id", nil]);
    
    
    
    detailViewController.chart = chart;
    
    
    
	[self.navigationController pushViewController:detailViewController animated:YES];
}

- (IBAction)chartClick:(id)sender
{
//    KxMenuItem *first = self.menuItems[0];
//    first.foreColor = [UIColor colorWithRed:47/255.0f green:112/255.0f blue:225/255.0f alpha:1.0];
//    first.alignment = NSTextAlignmentCenter;
//    
//    [KxMenu showMenuInView:self.view
//                  fromRect:((UIButton *)sender).frame
//                 menuItems:self.menuItems];
    
    NSInteger numberOfOptions = self.menuItems.count;
    RNGridMenu *av = [[RNGridMenu alloc] initWithItems:[self.menuItems subarrayWithRange:NSMakeRange(0, numberOfOptions)]];
    av.delegate = self;
    //    av.bounces = NO;
    [av showInViewController:self center:CGPointMake(self.view.bounds.size.width/2.f, self.view.bounds.size.height/2.f)];

}

- (IBAction)classClick:(id)sender
{
    RankListViewController *detailViewController = [[RankListViewController alloc] initWithNibName:@"RankListViewController" bundle:nil];
    
	[self.navigationController pushViewController:detailViewController animated:YES];
    
    detailViewController.condition = self.condition;
    detailViewController.rank_Div = @"1";
}
- (IBAction)gradeClick:(id)sender
{
    RankListViewController *detailViewController = [[RankListViewController alloc] initWithNibName:@"RankListViewController" bundle:nil];
    
	[self.navigationController pushViewController:detailViewController animated:YES];
    
    detailViewController.condition = self.condition;
    detailViewController.rank_Div = @"2";
    
}

/**
 *读取考试信息
 */
-(void) loadTestInfo :(Record*) info
{
    self.stuName.text = [info getFieldValueByName:@"stu_Name"];
    UIImage *img=[UIImage imageWithData:[info getFieldDataByName:@"stu_Img"]];
    self.imgView.image =img;
    
    NSString *ptn_Id = [self.condition getFieldValueByName:@"ptn_Id"];
    
    NSString *stu_Id = [info getFieldValueByName:@"stu_Id"];
    
    NSString *class_Id = [info getFieldValueByName:@"class_Id"];
    NSString *class_Ym = [info getFieldValueByName:@"class_Ym"];
    NSString *class_Div = [info getFieldValueByName:@"class_Div"];
    
    NSString *querySql = [NSString stringWithFormat:@"select * from T_Rank where ptn_Id ='%@' and stu_Id = '%@' and (class_Id = '%@' or (class_Id is null and class_Ym = '%@' and class_Div = '%@')) and rank_Type='2'  " ,ptn_Id,stu_Id,class_Id,class_Ym,class_Div];
    
    const char *sql = [querySql UTF8String];
    
    NSMutableArray * ranks = getDbRecords(sql,@"T_Rank",[NSArray arrayWithObjects:@"Rank_Id", nil]);
    
    for(Record *recordStt in ranks){
        if([[recordStt getFieldValueByName:@"rank_Div"] isEqual:@"1"]){
            self.score.text = [recordStt getFieldValueByName:@"R_Souce"];
            self.classRank.text = [recordStt getFieldValueByName:@"rank"];
        }else if([[recordStt getFieldValueByName:@"rank_Div"] isEqual:@"2"]){
            self.gradeRank.text = [recordStt getFieldValueByName:@"rank"];
        }
    }

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void) showPM
{
    RankViewController *detailViewController = [[RankViewController alloc] initWithNibName:@"RankViewController" bundle:nil];
    
	[self.navigationController pushViewController:detailViewController animated:YES];
    detailViewController.condition = self.condition;

}

- (void) hiddenPMbtn
{
    self.navigationItem.rightBarButtonItem = nil;
}


#pragma mark -
#pragma mark Table Data Source Methods
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}
- (NSInteger)tableView:(UITableView *)tableView
 numberOfRowsInSection:(NSInteger)section
{
    [self getRecords];
    return [self.datas count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"ScoreListCellIdentifier";
    
    ScoreListCell *cell = (ScoreListCell *)[tableView
                                    dequeueReusableCellWithIdentifier: cellIdentifier];
    if (cell == nil)
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ScoreListCell"
                                                     owner:self options:nil];
        for (id oneObject in nib)
            if ([oneObject isKindOfClass:[ScoreListCell class]])
                cell = (ScoreListCell *)oneObject;
    }
    
	
    NSUInteger row = [indexPath row];
    
    //图片index计算
    Record *data =[self.datas objectAtIndex:row];
    NSUInteger index = [[data getFieldValueByName:@"lesson_Cd"] intValue];
    if(index > self.imgNames.count-1)
    {
        index = 0;
    }
    
    
    [cell setData:data index:row imgName:[self.imgNames objectAtIndex:index]];
    
    [self configureCell:cell indexPath:indexPath accessoryType:DISCLOSURE_INDICATOR];
    
    return cell;
}

#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    // Navigation logic may go here. Create and push another view controller.
	
	ScoreDetailViewController *detailViewController = [[ScoreDetailViewController alloc] initWithNibName:@"ScoreDetailViewController" bundle:nil];
    
	// Pass the selected object to the new view controller.
	
	if (tableView == self.searchDisplayController.searchResultsTableView){
        //		detailViewController.currentLineName = [filteredListContent objectAtIndex:indexPath.row];
        //		detailViewController.currentLineIndex = [[CDataContainer Instance].lineNameArray indexOfObject:[filteredListContent objectAtIndex:indexPath.row]];
	}
	else{
        //		detailViewController.currentLineName = [[CDataContainer Instance].lineNameArray objectAtIndex:indexPath.row];
        //		detailViewController.currentLineIndex = indexPath.row;
	}
    
    NSUInteger row = [indexPath row];
    
    [detailViewController setData:[self.datas objectAtIndex:row]];
    detailViewController.studentInfo = self.studentInfo;
    
	[self.navigationController pushViewController:detailViewController animated:YES];
    
}

-(void)getRecords
{
    NSString *ptnId = [self.condition getFieldValueByName:@"ptn_Id"];
    NSString *stuId = [userEntry.userInfo getFieldValueByName:@"stu_Id"];
    
    if(isSelfInfo == false){
        stuId = [self.studentInfo getFieldValueByName:@"stu_Id"];
    }else{
        self.studentInfo = userEntry.userInfo;
    }
    
    NSString *querySql = [NSString stringWithFormat:@"select T1.* ,T5.Tch_Id,T5.Tch_Name ,T3.* ,T4.* from T_Result T1 left join T_LessonTch T2 on T1.Lesson_Tch_Id = T2.Lesson_Tch_Id left join T_Lesson T3 on T2.Lesson_Id = T3.Lesson_Id left join M_Lesson T4 on T3.Lesson_Cd = T4.Lesson_Cd left join M_Teacher T5 on T2.Tch_Id = T5.Tch_Id where T1.ptn_Id ='%@' and T1.stu_Id = '%@' " ,ptnId,stuId];
    
    const char *sql = [querySql UTF8String];
    
    self.datas = getDbRecords(sql,@"T_Result",[NSArray arrayWithObjects:@"R_Id", nil]);
}


//==========================================================
-(void) openChar:(NSString *) title div:(NSString *) rank_Div  type:(NSString *)type  seriesType:(NSString *)seriesType valueReverse :(BOOL)valueReverse
{
    
    ChartViewController *detailViewController = [[ChartViewController alloc] initWithNibName:@"ChartViewController" bundle:nil];
    
    LineNodeChart *chart = [[LineNodeChart alloc]init];
    
    //DATA
    NSString *lessonSql = [NSString stringWithFormat:@"select distinct T1.lesson_Tch_Id ,T4.* "
                           "from T_Rank T1 left join T_LessonTch T2 on T1.lesson_Tch_Id = T2.lesson_Tch_Id left join T_Lesson T3 on T2.lesson_ID = T3.lesson_ID left join M_Lesson T4 on T3.lesson_CD = T4.lesson_CD where  T1.stu_Id = '%@' and T2.lesson_Tch_Id is not null " ,[userEntry.userInfo getFieldValueByName:@"stu_Id"]];
    
    const char *lessql = [lessonSql UTF8String];
    
    NSMutableArray * lessons = getDbRecords(lessql,@"T_Rank",[NSArray arrayWithObjects:@"Rank_Id", nil]);
    
    
    NSString *querySql = [self getNodesDataSqlWithType:type lessons:lessons rank_Div:rank_Div];
    
    const char *sql = [querySql UTF8String];
    
    chart.title = title;
    chart.seriesType = seriesType;
    chart.valueReverse = valueReverse;
    chart.dataSource = getDbRecords(sql,@"T_Rank",[NSArray arrayWithObjects:@"Rank_Id", nil]);
    
    chart.categoryAxisField = @"TP_Name";
    
    [chart addSeries:@"总分" name:@"总分"];
    for (Record * les in lessons) {
        if([[les getFieldDataByName:@"lesson_Tch_Id"] isEqual:@""]){
//            [chart addSeries:@"总分" name:@"总分"];
        }else{
            [chart addSeries:[les getFieldValueByName:@"lesson_Name"] name:[les getFieldValueByName:@"lesson_Name"]];
        }
        
    }
    
    detailViewController.chart = chart;
    
    
    
	[self.navigationController pushViewController:detailViewController animated:YES];
}

- (NSString *) getNodesDataSqlWithType :(NSString *) type lessons:(NSMutableArray *) lessons rank_Div:(NSString *)rank_Div
{
    NSMutableString *tmp = [NSMutableString stringWithCapacity:8];
    
    [tmp appendString:@"select "];
    
    [tmp appendFormat:@" sum( case when T1.rank_Type='2' then T1.%@ else 0 end) as '%@',"
     , type
     , @"总分"];
    
    
    for (Record * les in lessons) {
        
        if([[les getFieldValueByName:@"lesson_Tch_Id"] isEqual:@""]){
//            [tmp appendFormat:@" sum( case when T1.lesson_Tch_Id is null then T1.%@ else 0 end) as '%@',"
//             ,type, @"总分"];
        }else{
            [tmp appendFormat:@" sum( case when T1.lesson_Tch_Id ='%@' and  T1.rank_Type='1' then T1.%@ else 0 end) as '%@',"
             , [les getFieldValueByName:@"lesson_Tch_Id"],type
             , [les getFieldValueByName:@"lesson_Name"]];
        }
        
        
    }
    
    [tmp appendFormat:@" T1.ptn_Id ,T2.TP_Name  from T_Rank T1 left join T_TestPtn T2 on T1.ptn_Id = T2.ptn_Id where  T1.stu_Id = '1' and T1.rank_Div = '%@' group by T1.ptn_Id",rank_Div];
    
    
    return tmp;
}

@end
